<?php


/**
 *  Autoload function includes files according to the following convention:
 *  Class names replace "_" with "/" and append .php to the
 *  classname, then tries to include that file relative to the INCLUDES_DIR
 *  If the class of the original $className still does not exist, it throws an exception
 */
function AntzAutoLoad($className){
    if (class_exists($className, false)) {
            return true;
    };
    // now we see the purpose of the convention:
    global $gCms;
    $dirname = str_replace(DIRECTORY_SEPARATOR, '/', $gCms->config['root_path'].'/modules/Antz');
    $path = str_replace('_', '/', $className).'.php';
    if(!file_exists($dirname.'/'.$path) || !is_readable($dirname.'/'.$path)){
        return;
    } else {
        include($dirname.'/'.$path);
        if(!class_exists($className)){
            return false;
        }else{
            // we successfully found the file!
            return true;
        };
    };
}


/**
 * Global shorthand
 */
function post($key, $alt='', $strlen=255)
{
    $input = Antz::registry('input');
    $newval = $input->getPostValue($key, $strlen, false);
    if($newval !== false) return $newval;
    $newval = $input->getFilesValue($key, $strlen, false);
    if($newval !== false) return $newval;
    return $alt;
}
/**
 * Global shorthand
 */
function get($key, $alt='', $strlen=255)
{
    $input = Antz::registry('input');
    if($value = $input->getGetValue($key, $strlen, false)) return $value;
    return $alt;
}


/**
 * Array_Insert function to place a value into an array at a given position
 */
function array_insert ($input, $position, $value)
{
    // we will definitely get the result back in an array, pos 1
    if (!is_array ($input))
    {
        $array = array ($input);
        $array[$position] = $value;
        return $array;
    }
    // move each key higher to make room for the new key=>value set
    for ($i = count($input); $i > $position; $i--)
    {
        $input[$i] = $input[$i - 1];
    }
    // insert the value to the position
    $input[$position] = $value;

    return $input;
}


/**
 *  Regenerates keys so the first key is 0 and greatest key is (count($arr)-1),
 *  maintaining natural order of values
 */
function array_regenerate_keys($array)
{
    $count = 0;
    $arr2 = array();
    foreach($array as $v){
        $arr2[$count] = $v;
        $count++;
    };
    unset($array, $count);
    return $arr2;
}



